package com.greenantmall.activity.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.greenantmall.R;
import com.greenantmall.adapter.MyOrderListAdapter;
import com.greenantmall.bean.Order;
import com.greenantmall.bean.OrderList;
import com.greenantmall.bean.OrderStatusCode;
import com.greenantmall.service.RetrieveDataAsyn;
import com.greenantmall.service.RetrieveDataListener;
import com.greenantmall.utils.Const;
import com.greenantmall.utils.iLog;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class OrdersListFragment extends Fragment {
	private static final String TAG = "GoodsListFragment";

	/**
	 * 订单类型
	 */
	public static final int ORDER_TYPE_ALL = Order.ORDER_TYPE_ALL;
	public static final int ORDER_TYPE_UNPAY = OrderStatusCode.ORDER_WAIT_FOR_PAY
			.value();
	public static final int ORDER_TYPE_UNSEND = OrderStatusCode.ORDER_PENDING
			.value();
	public static final int ORDER_TYPE_UNRECEIVE = OrderStatusCode.ORDER_WAIT_FOR_SIGN
			.value();// 待收货，已配送和已配送至自提点和待收货
						// ORDER_SHIPPED(1), // 1-已发货 ORDER_2_STATION(2), //
						// 2-已送至自提点

	private int orderType = ORDER_TYPE_ALL;
	private String userId;
	private final static String TAG_ORDER_TYPE = "orderType";
	private final static String TAG_USER_ID = "userId";

	private final int expectedCount = 20;

	private List<Order> list = new ArrayList<Order>();
	MyOrderListAdapter myOrderListAdapter;
	private int totalItemCounts = 0;
	private boolean isGettingData = false;

	private TextView noOrderListHint;
	private ListView orderlistView;
	private RelativeLayout nodataView;

	public static OrdersListFragment newInstance(int orderType, String userId) {
		OrdersListFragment newFragment = new OrdersListFragment();
		Bundle bundle = new Bundle();
		bundle.putInt(TAG_ORDER_TYPE, orderType);
		bundle.putString(TAG_USER_ID, userId);
		newFragment.setArguments(bundle);
		return newFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getArguments();
		if (bundle != null) {
			orderType = bundle.getInt(TAG_ORDER_TYPE, ORDER_TYPE_ALL);
			userId = bundle.getString(TAG_USER_ID);
		}
		registerReciver();
	}

	private void registerReciver() {
		IntentFilter downloadManagerFilter = new IntentFilter();
		downloadManagerFilter.addAction(Const.ORDER_STATUS_CHANGED);
		this.getActivity().getBaseContext()
				.registerReceiver(netManagerReceiver, downloadManagerFilter);
	}

	private BroadcastReceiver netManagerReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (myOrderListAdapter != null) {
				myOrderListAdapter.notifyDataSetChanged();
			}
		}

	};

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Bundle bundle = this.getArguments();
		if (bundle != null) {
			orderType = bundle.getInt(TAG_ORDER_TYPE, ORDER_TYPE_ALL);
			userId = bundle.getString(TAG_USER_ID);
		}

		View contentView = inflater.inflate(R.layout.orderlist, container,
				false);
		orderlistView = (ListView) contentView
				.findViewById(R.id.orderlist);
//		ListView actualListView = orderlistView.getRefreshableView();
		noOrderListHint = (TextView) contentView
				.findViewById(R.id.noOrderListHint);
		nodataView = (RelativeLayout) contentView.findViewById(R.id.nodataView);
		myOrderListAdapter = new MyOrderListAdapter(list, getActivity());
		//orderlistView.setAdapter(myOrderListAdapter);
		orderlistView.setAdapter(myOrderListAdapter);
		orderlistView.setOnScrollListener(new AbsListView.OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (totalItemCount < totalItemCounts
						&& (firstVisibleItem + visibleItemCount) == (totalItemCount - 2)) {
					if (!isGettingData) {
						isGettingData = true;

						RetrieveDataAsyn.getInstance().getMyOrderByType(userId,
								orderType, list.size(), expectedCount, 0,
								new RetrieveDataListener() {

									@Override
									public void dataRetrieved(int requestId,
											Object data) {
										if (data != null) {
											OrderList orderList = (OrderList) data;
											totalItemCounts = orderList
													.getTotalNum();
											list.addAll(orderList
													.getOrderList());
											myOrderListAdapter
													.notifyDataSetChanged();
										}
										isGettingData = false;
									}
								});

					}

				}
			}
		});
		
//		orderlistView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {
//
//			@Override
//			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
//				firstInGetData();
//			}
//
//			@Override
//			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
//				
//			}
//		});
		//orderlistView.setRefreshing(true);
		firstInGetData();
		return contentView;
	}

	private void firstInGetData() {
		RetrieveDataAsyn.getInstance().getMyOrderByType(userId, orderType, 0,
				expectedCount, 0, new RetrieveDataListener() {

					@Override
					public void dataRetrieved(int requestId, Object data) {
//						orderlistView.onRefreshComplete();
						list.clear();
						refreshWithData();
						if (data != null) {

							OrderList orderList = (OrderList) data;
							totalItemCounts = orderList.getTotalNum();
							list.addAll(orderList.getOrderList());
							if (list.size() == 0) {
								refreshNoData();
							}
						} else {
							refreshNoData();
						}
						myOrderListAdapter.notifyDataSetChanged();
						
					}
				});
	}

	public void refreshNoData() {
		iLog.d(TAG,"refreshNoData:"+orderType);
		noOrderListHint.setVisibility(View.VISIBLE);
		orderlistView.setVisibility(View.INVISIBLE);
		nodataView.setVisibility(View.INVISIBLE);
	}

	public void refreshWithData() {
		iLog.d(TAG,"refreshWithData:"+orderType);
		noOrderListHint.setVisibility(View.INVISIBLE);
		orderlistView.setVisibility(View.VISIBLE);
		nodataView.setVisibility(View.INVISIBLE);
	}

	@Override
	public void onDestroy() {
		this.getActivity().getBaseContext()
				.unregisterReceiver(netManagerReceiver);
		super.onDestroy();
		Log.d(TAG, "MyStoreFragment-----onDestroy");
	}

}
